package com.nbjtjc.safe.service.safe;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nbjtjc.safe.bean.Constant;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.safe.SafeDangerInspectPlanMapper;
import com.nbjtjc.safe.mapper.safe.SafeEnterpriseMapper;
import com.nbjtjc.safe.mapper.sys.SysFileMapper;
import com.nbjtjc.safe.model.safe.SafeDangerInspectPlan;
import com.nbjtjc.safe.model.safe.SafeDangerInspectTaskRecord;
import com.nbjtjc.safe.model.safe.SafeEnterprise;
import com.nbjtjc.safe.model.sys.SysFile;
import com.nbjtjc.safe.util.BaiduOCRUtil;
import com.nbjtjc.safe.util.MyShiroUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class EnterpriseServiceImpl {

    @Autowired
    private SafeEnterpriseMapper safeEnterpriseMapper;

    @Autowired
    private SysFileMapper sysFileMapper;

    @Autowired
    private BaiduOCRUtil baiduOCRUtil;
    @Value("${aliyun.oss.domain}")
    private String ossDomain;

    @Autowired
    private SafeDangerInspectPlanServiceImpl planService;

    private List<Integer> enterpriseIdTypes = new ArrayList<>(Arrays.asList(Constant.SysFileType.ENTERPRISE_FILE.getValue()
            ,  Constant.SysFileType.FOUR_COLOR_RISK_CHART.getValue()
            , Constant.SysFileType.LOCATION_PIC.getValue(), Constant.SysFileType.SURROUNDING_PIC.getValue()
            , Constant.SysFileType.RISK_AREA_PIC.getValue()));

    @Autowired
    private SafeDangerInspectPlanMapper planMapper;

    public Result search(SafeEnterprise enterprise) {
        Result result = new Result();
        PageHelper.startPage(enterprise.getPageCurrent(), enterprise.getPageSize());
        List<SafeEnterprise> enterpriseList = safeEnterpriseMapper.search(enterprise);
        List<Integer> enterpriseIds = enterpriseList.parallelStream()
                .map(SafeEnterprise::getId).collect(Collectors.toList());

//        List<SysFile> sysFiles = sysFileMapper.findByContentIds(enterpriseIds, Constant.SysFileType.ENTERPRISE_FILE.getValue());
        List<SysFile> sysFiles = sysFileMapper.findByContentIdsAndContentTypes(enterpriseIds, enterpriseIdTypes);
        compareEnterpriseList(enterpriseList, sysFiles);
        Map<Integer, SafeEnterprise> idMap = compareEnterpriseList(enterpriseList, sysFiles);
        result.setData(new PageInfo<>(enterpriseList));
        return result;
    }

    private Map<Integer, SafeEnterprise> compareEnterpriseList(List<SafeEnterprise> enterpriseList, List<SysFile> sysFiles) {
        Map<Integer, SafeEnterprise> idMap = enterpriseList.stream()
                .collect(Collectors.toMap(SafeEnterprise::getId, safeEnterprise -> safeEnterprise));
        if (CollectionUtil.isNotEmpty(enterpriseList) && CollectionUtil.isNotEmpty(sysFiles)) {
            sysFiles.forEach(sysFile -> {
                if (idMap.containsKey(sysFile.getContentId())) {
                    SafeEnterprise safeEnterprise = idMap.get(sysFile.getContentId());
                    if (sysFile.getFileKey().equals(safeEnterprise.getFileKey())) {
                        sysFile.setUrl(ossDomain + "/" + sysFile.getPath() + "?x-oss-process=image/resize,m_fixed,h_70,w_70");
                        sysFile.setOriUrl(ossDomain + "/" + sysFile.getPath());
                        idMap.get(sysFile.getContentId()).getBusinessPics().add(sysFile);
                        idMap.get(sysFile.getContentId()).getBusFileUrls().add(sysFile.getOriUrl());
                        idMap.get(sysFile.getContentId()).setBusinessFile(sysFile);
                    }

                    if (sysFile.getContentType().equals(Constant.SysFileType.FOUR_COLOR_RISK_CHART.getValue())) {
                        sysFile.setUrl(ossDomain + "/" + sysFile.getPath() + "?x-oss-process=image/resize,m_fixed,h_70,w_70");
                        sysFile.setOriUrl(ossDomain + "/" + sysFile.getPath());
                        safeEnterprise.setFourColorRiskPicFile(sysFile);
                        safeEnterprise.getFourColorRiskPicList().add(sysFile.getOriUrl());
                    }
                    if (sysFile.getContentType().equals(Constant.SysFileType.LOCATION_PIC.getValue())) {
                        sysFile.setUrl(ossDomain + "/" + sysFile.getPath() + "?x-oss-process=image/resize,m_fixed,h_70,w_70");
                        sysFile.setOriUrl(ossDomain + "/" + sysFile.getPath());
                        safeEnterprise.setLocationPicFile(sysFile);
                        safeEnterprise.getLocationPicFileList().add(sysFile.getOriUrl());

                    }
                    if (sysFile.getContentType().equals(Constant.SysFileType.SURROUNDING_PIC.getValue())) {
                        sysFile.setUrl(ossDomain + "/" + sysFile.getPath() + "?x-oss-process=image/resize,m_fixed,h_70,w_70");
                        sysFile.setOriUrl(ossDomain + "/" + sysFile.getPath());
                        safeEnterprise.setSurroundingPicFile(sysFile);
                        safeEnterprise.getSurroundingPicFileList().add(sysFile.getOriUrl());

                    }
                    if (sysFile.getContentType().equals(Constant.SysFileType.RISK_AREA_PIC.getValue())) {
                        sysFile.setUrl(ossDomain + "/" + sysFile.getPath() + "?x-oss-process=image/resize,m_fixed,h_70,w_70");
                        sysFile.setOriUrl(ossDomain + "/" + sysFile.getPath());
                        safeEnterprise.setRiskAreaPicFle(sysFile);
                        safeEnterprise.getRiskAreaPicFileList().add(sysFile.getOriUrl());

                    }
                }
            });
        }

        return idMap;
    }


    public Result add(SafeEnterprise safeEnterprise) {
        Result result = new Result();
        safeEnterprise.setCreateUserId(MyShiroUtils.getSessionUserId());
        safeEnterprise.setCreateUser(MyShiroUtils.getSessionUserName());
        safeEnterprise.setChargeUserId(MyShiroUtils.getSessionUserId());
        safeEnterprise.setCreateTime(new Date());
        safeEnterpriseMapper.insert(safeEnterprise);
        if (StringUtils.isNotEmpty(safeEnterprise.getFileKey())) {
            SysFile sysFile = new SysFile();
            sysFile.setFileKey(safeEnterprise.getFileKey());
            List<SysFile> fileList = sysFileMapper.select(sysFile);
            if (CollectionUtil.isNotEmpty(fileList)) {
                fileList.forEach(file -> {
                    file.setContentId(safeEnterprise.getId());
                    sysFileMapper.updateByPrimaryKeySelective(file);
                });
            }
        }
        result.setData(safeEnterprise);
        return result;
    }

    public Result update(SafeEnterprise safeEnterprise) {
        Result result = new Result();
        safeEnterpriseMapper.updateByPrimaryKeySelective(safeEnterprise);
        result.setData(safeEnterprise);
        return result;
    }

    @Transactional
    public Result delete(int id) {
        Result result = new Result();
        safeEnterpriseMapper.deleteByPrimaryKey(id);
        SafeDangerInspectPlan plan = new SafeDangerInspectPlan();
        plan.setEnterpriseId(id);
        List<SafeDangerInspectPlan> planList = planMapper.search(plan);
        if (CollectionUtil.isNotEmpty(planList)) {
            planList.forEach(safePlan -> {
                planService.delete(safePlan);
            });
        }
        return result;
    }


    public Result businessLicense(String fileKey) {
        Result result = new Result();
        SysFile sysFile = new SysFile();
        sysFile.setFileKey(fileKey);
        List<SysFile> sysFiles = sysFileMapper.select(sysFile);
        if (CollectionUtil.isNotEmpty(sysFiles)) {
            sysFile = sysFiles.get(0);
            JSONObject jsonObject = baiduOCRUtil.businessLicense(sysFile).getJSONObject("words_result");
            SafeEnterprise safeEnterprise = new SafeEnterprise();
            String code = jsonObject.getJSONObject("社会信用代码").getString("words");
            if (!code.equals("无")) {
                safeEnterprise.setOrganizationCode(code);
            }
            String fr = jsonObject.getJSONObject("法人").getString("words");
            if (!code.equals("无")) {
                safeEnterprise.setLegalPerson(fr);
            }
            String address = jsonObject.getJSONObject("地址").getString("words");
            if (!code.equals("无")) {
                safeEnterprise.setAddress(address);
            }
            String name = jsonObject.getJSONObject("单位名称").getString("words");
            if (!code.equals("无")) {
                safeEnterprise.setName(name);
            }
            result.setData(safeEnterprise);
        } else {
            result.setFalse();
        }
        return result;
    }
}
